package org.zjt.platform.springbootreactivedemo.component;

import org.zjt.platform.springbootreactivedemo.service.PersonService;
import org.zjt.platform.springbootreactivedemo.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromPublisher;

/**
 * @author <a href="juntao.zhang@qq.com">juntao.zhang</a>
 * @Description:
 * @Package org.zjt.platform.springbootreactivedemo.component
 * @date 2018/3/15 11:07
 * @see
 */
@Component
public class PersonHandler {

    @Autowired
    private PersonService personService;

    public Mono<ServerResponse> getPerson(ServerRequest request){
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromPublisher(personService.getPerson(request).map(JsonResult::OK),JsonResult.class));
    }

    public Mono<ServerResponse> savePerson(ServerRequest request){
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(fromPublisher(personService.savePerson(request)
                        .map(result -> result ? JsonResult.OK() : JsonResult.ERROR("保存失败")),JsonResult.class));
    }

    public Mono<ServerResponse> deletePerson(ServerRequest request){
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .build(personService.deletePerson(request))
                .onErrorReturn(ServerResponse.ok().syncBody(JsonResult.ERROR("保存失败")).block());
    }
}
